package com.sinotrans.common.rest;

import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

public class RestClient {
	final static String http = "http://";
	final static String https = "https://";

	/**
	 * 提交表单
	 * 
	 * @param restTemplate
	 * @param uri
	 * @param head
	 * @param param
	 * @param clazz
	 * @return
	 * @throws Exception
	 */
	public static <T> T postForm(RestTemplate restTemplate, String uri, MultiValueMap<String, String> head,
			MultiValueMap<String, String> param, Class<T> clazz) throws Exception {
		if (uri.startsWith("/")) {
			uri = uri.substring(1);
		}
		StringBuilder url = new StringBuilder();
		if (!(uri.startsWith(http) || uri.startsWith(https))) {
			url.append(http);
		}
		url.append(uri);
		//
		HttpHeaders headers = new HttpHeaders();
		headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
		if (head != null) {
			headers.addAll(head);
		}
		//
		HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<MultiValueMap<String, String>>(param,
				headers);
		ResponseEntity<T> response = restTemplate.postForEntity(url.toString(), request, clazz);
		return response.getBody();
	}
}
